const axios = require('axios');
const xml2json = require('xml2json');
const parseString = require('xml2js').parseString;
const db = require("./db")
axios.defaults.baseURL = 'http://127.0.0.1:8222/';
axios.defaults.timeout = 2500;

async function getCanUseIp() {
    let { data } = await axios.get('getStableLines/');
    let json = xmlToJson(data);
    console.log(json)
    let areadList = await db.getIp();
    let ips = [];
    for (const iterator of json.line.server) {
        const flag = findIsIn(iterator, areadList);       
        if (!flag) {
            ips.push(iterator);
        }
    }

    return ips;
}

async function conectIP(name) {
    let { data } = await axios.get("connect/", {
        params: {
            servername: name,
            linktype: '0/'
        }
    });
    let json = xmlToJson(data);
    return json;
}

async function tunIP(ip) {
    await conectIP(ip.name)    
   return  new Promise(function (resolve, reject) {
        let t = setInterval(async function () {
            let msg = await getCurState();
            if (msg.state = 1) {
                clearInterval(t);
                resolve(msg);
            }
        }, 1000)
    })
}

function findIsIn(ele, list) {
    for (const iterator of list) {
        if (ele.ip == iterator.ip) {
            return true;
        }
    }
    return false;
}

async function getCurState() {
    let { data } = await axios.get('getstate/');
    let json = xmlToJson(data);
    return json;
}




const options = {
    object: true,
    reversible: false,
    coerce: false,
    sanitize: true,
    trim: true,
    arrayNotation: false,
    alternateTextNode: false
};
function xmlToJson(xml) {

    let result = xml2json.toJson(xml, options);

    if (result.hasOwnProperty('root')) {
        return (result.root)
    } else {
        return (result)
    }
}


module.exports = {
    tunIP,
    getCurState,
    getCanUseIp,
}


// async function app() {
//     await tunIp();
//     await getCurState();
// }

// app();